local game = require "club.threecard.blackjack"
local PointIndicator = require "club.threecard.blackjack.ui.ingame.PointIndicator"

local Vector3 = CS.UnityEngine.Vector3
local Color = CS.UnityEngine.Color
local poker_amount = game.util.poker_amount

local white = Color.white
local red = Color.red
local pos_zero = Vector3.zero

local M = game.ui.element(game.pokerlib.core.poker_container)

function M:ctor(config, no)
    self.no = no
    self.point_indicator = PointIndicator.new(self)
end

function M:on_injected(bind)
    bind("gameobject.element", self.point_indicator_obj, self.point_indicator)
end

function M:clear()
    self:super("clear")
    self.point_indicator:hide()
    self.transform.localPosition = pos_zero
end

function M:mopai(serverValueTable, over_handler)
    if not self.loaded then
        self.should_mopai_t  = serverValueTable
        return
    end

    if self.config.mopai_anim then
        self.config.mopai_anim(self, serverValueTable, function()
            self:update_poker_amount()
        end)    
    end
end

function M:confirm_amount()
    self.point_indicator:update()
    self:_update_amount_pos()
end

function M:update_poker_amount()
    self.point_indicator:update()
    self:_update_amount_pos()
end

function M:hide_amount()
    self.point_indicator:hide()
end

function M:show_amount()
    self.point_indicator:show()
end

function M:split_to(container)
    if #self.hand % 2 ~= 0 then
        game.gamelib.log.error("分牌错误， 当前手牌Count："..#self.hand)
        return
    end

    local other_half = {}
    for i = #self.hand/2+1, #self.hand do
        local poker = self.hand[i]
        table.insert(other_half, poker.data.server_value)
    end

    self:chupai(other_half)
    self:clear_chupai()
    self:update_poker_amount()

    container:fill(other_half)
    container:update_poker_amount()
end

function M:_update_amount_pos()
    local x = 0
    local y = 99999999
    local z = 0
    local s = 1
    if #self.hand >=6 then
        s = 6
    elseif #self.hand >=4 then
        s = 4
    else
        s = 1
    end

    if self.no == -1 then
        s = 1
    end

    for i = s, #self.hand do
        local poker = self.hand[i]
        x = poker.flag_root.position.x + x
        if y > poker.flag_root.position.y then
            y = poker.flag_root.position.y
        end
        z = poker.transform.position.z
    end
    x = x/(#self.hand-s+1)
    self.point_indicator:set_world_position(Vector3(x, y, z))
end

function M:on_release()
    self:super("on_release")
    self.point_indicator:release()
end

return M